import { useSetState, useUpdateEffect } from 'ahooks';
import { groupBy } from 'lodash';
// import store from '@/assets/map/store.png';
import { types, codes, setDataType } from './configs';
import { useState } from 'react';
import useHeatMap from '@/utils/marketingMap/useHeatMap';
import { store_icon } from '@/utils/marketingMap/utils';

interface StoreProps {
  lon: string;
  lat: string;
  code: string;
  name: string;
  vehicleCount: number;
  aftersalesCount: number;
  recentYearCustomerCount: number;
}

const ICON_SIZE = 24;
const zoom = 14.5;

const useMap = (data: any, isAuth = true, selected: string[], selectedChild: string[]) => {
  const [status, setStatus] = useState(false);

  const [state, setState] = useSetState<any>({});
  const [massMarksByType, setMassMarksByType] = useSetState<any>({});
  const [isType, setIsType] = useState(true);

  const { map, AMap, infoWindow, overlayGroup } = state;
  const { heatMap, setHeatMapData } = useHeatMap(AMap, map);

  const onRenderingCompleted = (map: any, AMap: any) => {
    const overlayGroup = new AMap.OverlayGroup({});

    const infoWindow = new AMap.InfoWindow({
      offset: new AMap.Pixel(0, -20),
      closeWhenClickMap: true,
      autoMove: true,
    });
    map.on('zoomend', () => {
      if (map.getZoom() > zoom) {
        setStatus(true);
      } else {
        setStatus(false);
      }
    });

    setState({
      map,
      AMap,
      infoWindow,
      overlayGroup,
    });
  };
  const markerClick = (content: string, position: any) => {
    infoWindow.setContent(content);
    infoWindow.open(map, position);
  };
  const setMassMarks = (data: { [x: string]: any }[], isType: boolean) => {
    let style = null;

    if (isType) {
      style = types.map((_, index) => ({
        url: `/map/type/${index}.png`,
        anchor: new AMap.Pixel(6, 6),
        size: new AMap.Size(ICON_SIZE, ICON_SIZE),
        zIndex: 4,
      }));
    } else {
      style = codes.map((_, index) => ({
        url: `/map/${index}.png`,
        anchor: new AMap.Pixel(6, 6),
        size: new AMap.Size(ICON_SIZE, ICON_SIZE),
        zIndex: 4,
      }));
    }

    const result = data.map(({ lon, lat, ...other }) => ({
      lnglat: [lon, lat],
      style: isType ? types.indexOf(other.category) : codes.indexOf(other.subCategory),
      ...other,
    }));
    const massMarksByDataType = groupBy(result, isType ? 'category' : 'subCategory');

    const massMarksByType: any = {};

    for (let type in massMarksByDataType) {
      massMarksByType[type] = new AMap.MassMarks(massMarksByDataType[type], {
        opacity: 0.8,
        zIndex: 111,
        cursor: 'pointer',
        style: style,
      });

      massMarksByType[type].setMap(map);

      if (isType) {
        if (selected.includes(type)) {
          massMarksByType[type].show();
        } else {
          massMarksByType[type].hide();
        }
      } else {
        if (selectedChild.includes(type)) {
          massMarksByType[type].show();
        } else {
          massMarksByType[type].hide();
        }
      }
      setMassMarksByType(massMarksByType);
    }
  };

  useUpdateEffect(() => {
    if (heatMap && map) {
      const { distributionData, storeData: stora } = data || {};

      if (stora) {
        overlayGroup.clearOverlays();
        map.clearMap();

        map.setCenter([stora.lon, stora.lat]);

        const labelMarker = new AMap.LabelMarker({
          position: [stora.lon, stora.lat],
          icon: store_icon,
        });

        const content = new AMap.Marker({
          position: [stora.lon, stora.lat],
          content: `
            <div class="infoWindow">
              <span>${isAuth ? stora.name : '我的专营店'}</span>
            <div/>
          `,
          offset: new AMap.Pixel(-50, -50), // 偏移位置
        });
        const activeMap = distributionData;

        overlayGroup.addOverlays([labelMarker, content]);

        setMassMarks(activeMap, isType);

        const heatMapData = distributionData.map(
          (item: Pick<StoreProps, 'lon' | 'lat' | 'vehicleCount'>) => ({
            lng: item.lon,
            lat: item.lat,
            count: item.vehicleCount,
          }),
        );

        setHeatMapData(heatMapData);

        map.add(overlayGroup);
      } else {
        map?.clearMap();
        setHeatMapData([]);
      }
    }
  }, [data, map, heatMap, isAuth, isType]);

  useUpdateEffect(() => {
    if (status) {
      selected.forEach(key => {
        massMarksByType[key]?.show();
      });
      selectedChild.forEach(key => {
        massMarksByType[key]?.show();
      });
    } else {
      selected.forEach(key => {
        massMarksByType[key]?.hide();
      });
      selectedChild.forEach(key => {
        massMarksByType[key]?.hide();
      });
    }
  }, [status, massMarksByType]);
  return {
    onRenderingCompleted,
    massMarksByType,
    setIsType,
    status,
    map,
    markerClick,
  };
};

export default useMap;
